/**
 * A 3 x 3 Tic-Tac-Toe board.
 */
public class TicTacToe {
	/**
	 * Constructs an empty board.
	 */
	public TicTacToe() {
		board = new char[ROWS][COLUMNS];

		// fill with spaces
		for (int i = 0; i < ROWS; i++)
			for (int j = 0; j < COLUMNS; j++)
				board[i][j] = ' ';
	}

	/**
	 * Sets a field in the board. The field must be unoccupied.
	 * 
	 * @param i
	 *            the row index
	 * @param j
	 *            the column index
	 * @param player
	 *            the player ("x" or "o")
	 */
	public boolean set(int i, int j, char player) {
		if (board[i][j] != ' ')
			return false;
		board[i][j] = player;
		return true;
	}

	/**
	 * Creates a string representation of the board such as |x o| | x | | o|
	 * 
	 * @return the string representation
	 */
	public String toString() {
		String r = "  ";
		for (int j = 0; j < COLUMNS; j++)
			r += j;
		r += "\n";
		for (int i = 0; i < ROWS; i++) {
			r += i;
			r += "|";
			for (int j = 0; j < COLUMNS; j++)
				r += board[i][j];
			r += "|\n";
		}
		return r;
	}

	/**
	 * Gets the winner
	 * 
	 * @return the winner
	 */
	public char getWinner() {
		// check rows
		for (int r = 0; r < ROWS; r++) {
			char first = board[r][0];
			for (int c = 0; c < COLUMNS; c++)
				if (board[r][c] != first)
					first = ' ';
			if (first != ' ')
				return first;
		}
		// check columns
		for (int c = 0; c < COLUMNS; c++) {
			char first = board[0][c];
			for (int r = 0; r < ROWS; r++)
				if (board[r][c] != first)
					first = ' ';
			if (first != ' ')
				return first;
		}
		// check diagonals
		int centerRow = ROWS / 2;
		int centerColumn = COLUMNS / 2;

		if (centerRow == centerColumn) {
			char first = board[centerRow][centerColumn];
			for (int i = 0; i < Math.min(ROWS, COLUMNS); i++) {
				if (board[i][i] != first)
					first = ' ';
			}
			if (first != ' ')
				return first;
			for (int i = 0; i < Math.min(ROWS, COLUMNS); i++) {
				if (board[i][ROWS - i-1] != first)
					first = ' ';
			}
			if (first != ' ')
				return first;
		}
		return ' ';
	}

	private char[][] board;
	private static final int ROWS = 3;
	private static final int COLUMNS = 3;
}
